<style>
.btn-min{
	min-width: 77px;
}
.share-bar{
	font-size: 0.8em;
}
	
/* 商品详情，评价  */
.product-detail header {
  display: -webkit-box;
  display: box;
  height: 2.857em;
  border: 1px solid #ccc;
  border-top: none;
  border-bottom: none;
  background-color: #e9e9e9;
  box-shadow: 0 1px 2px rgba(0,0,0,.2);
  text-align: center;
  line-height: 2.857em;
}

.product-detail header a {
  display: block;
  border-top: 1px solid #ccc;
  -webkit-box-flex: 1;
}

.product-detail header a.current {
  background-color: #fff;
  border-top-color: #b10000;
  border-top-width: 2px;
}

.product-detail .wrap {
  overflow: hidden;
  border: 1px solid #ccc;
  border-top: none;
  background-color: #fff;
  word-wrap: break-word;
  padding-top: 1em;
}

#product-content{
	margin-bottom: 10px;
}

#product-content p{
	padding: 0 10px 10px;
}

.product-comment li {
  border-bottom: 1px solid #ccc;
  padding-bottom: .3em;
  margin-bottom: .7em;
  margin: 0 10px 10px;
  border: #ddd solid 1px;
  padding: 10px;
  border-radius: 3px;
}

.product-comment li .user {
  margin-top: .8em;
  font-size: .8em;
  padding-top: 5px;
  border-top: #ddd dashed 1px;
}

.product-comment li .user time {
  float: right;
  color: #555;
}
#product-comment-list {
	text-align: center;
	padding: 20px;
}
del{
    color: #999;
    font-size: 70%;
}
.float-right{
    float: right;
}
.color-red{
    color: red;
}
.text-underline{
    text-decoration: underline;
}
</style>

<!-- TOPBAR -->
<header class="top-bar flex-row">
  <span class="row-item row-item-auto top-bar-back" onclick="window.history.back()">返回</span>
  <h3 class="row-item top-bar-name">{$shopPackage.name}</h3>
  <a class="row-item row-item-auto top-bar-menu" href="{$config.url}">主页</a>
</header>

<include file="headerBar"/>

<!-- 商品图片 -->
<section class="pr-detail-header">

<style type="text/css">
.gh-tip {
	position: relative;
}
</style>
  
  <div class="swiper-container">
    <figure class="tc swiper-wrapper">
        <div class="swiper-slide">
          <img src="{$shopPackage['image']}" alt="">
        </div>
    </figure>  
  </div>

</section>

<section class="pr-detail pr-detail-info">

  <header class="flex-row">
    <div class="row-item row-item-6"><notempty name="shopGoods.description"><h3>{$shopPackage.description}</h3></notempty></div>
  </header>
  <header class="flex-row">
    <div class="row-item row-item-6">
      <p class="pr-info-now-price"><small>微信价:￥{$shopPackage.price}</small></p>
    </div>

    <div class="row-item row-item-4">
      <p class="pr-info-saled">{$shopPackage['saled_count']+$shopPackage['saled_base']}人已购买</p>
    </div>  
  </header>
  
</section>

<section class="pr-detail" style="margin-bottom: -1px;">
  
  <h5 class="pr-detail-title">选择商品类型</h5>

  <section id="pr-buy-check" class="pr-detail-content">
      
    <form id="pr-form" method="post" action="{:U('DisShopAgentOrder/confirmOrder')}">

      <!-- 类型 -->
      <foreach name="shopGoods.attrs_cfg" item="vo" key="key">

      <dl class="pr-check-item pr-check-attr">
        <dt class="pr-check-key" data-null="请选择{$key}">{$key}:</dt>
        <dd class="pr-check-value">
          <foreach name="vo" key="key1" item="vo1">
          <input hidden type="radio" id="{$key1}|{$vo1}" value="{$key1}|{$vo1}">
          <label class="pr-check-value-item" for="{$key1}|{$vo1}">{$vo1}</label>
          </foreach>
        </dd>
      </dl>

      </foreach>
      
      <!-- 购买数量 -->
      <dl class="pr-check-item">
        <dt class="pr-check-key">数量:</dt>
        <dd class="pr-check-value">
          <p class="pr-num flex-row">
            <span id="buy-num-minus" class="pr-num-minus row-item row-item-3" data-type="m">-</span>
            <input id="buy-num" class="pr-num-input row-item row-item-4" readonly="readonly" value="1">
            <span id="buy-num-plus" class="pr-num-plus row-item row-item-3" data-type="p">+</span>
          </p>
        </dd>
      </dl>
	  <div id="submit-data" style="display:none;">
			  
	  </div>
    </form>
    
  </section>

</section>

<section id="pr-action" class="pr-buy-action">
<p>
  <a id="pr-buynow" class="btn btn-min btn-action-red" href="javascript:;" data-jump="1">立即购买</a>
</p>
</section>

<section class="product-item product-detail" style="margin-top:25px;">
    <header id="product-tab">
      <a href="javascript:;" class="current" data-id="product-content">商品详情</a>
      <!--<a href="javascript:;" data-id="product-comment">商品评价</a>-->
    </header>
    <div class="wrap pd10" id="product-content" style="">
     	<ul>
     	<volist name="shopPackage['goodsList']" id="goods">
     	<li>
     		<div><img src="{$goods['images'][0]}"></div>
     		<div>{$goods['name']}</div>
     		<div>微信价：{$goods['price']}</div>
     		<div>件数：{$goods['count']}</div>
     	</li>
     	</volist>
     	</ul>
    </div>
    <div class="wrap pd10" id="product-comment" style="display:none;">
    <!-- 评论start -->
  	<div id="product-comment-list">暂无评论</p>
    <!-- 评论end -->
    </div>
  </section>

<link rel="stylesheet" href="__COMMON__/swiper/idangerous.swiper.css">
<script src="__PUBLIC__/Static/js/simapp.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  function toArray( data, level, path, result ) {
    for(var o in data) {
      var p = path + (level? "["+o+"]" : o);
      if (Object.prototype.toString.call(data[o]) === '[object Array]' || Object.prototype.toString.call(data[o]) === '[object Object]') {
        this.toArray(data[o],1 + level, p, result);
      } else {
          Object.prototype.toString.call(result) === '[object Object]' && (result[p] = data[o]);
          Object.prototype.toString.call(result) === '[object Array]' && result.push( p + "=" + data[o] );
        }
    };
    return result;
  }
  
  var id={$shopPackage.id},sid={$sid};  
  
  (function(){
      
      $("#btn-distribution").click(function(){
          simapp.tips("金牌会员分享朋友或朋友圈，如果朋友购买，您就可以获得积分奖励啦！");
      })
    
    // 选择属性
    $("#pr-buy-check input[type=radio]").on("change", selectAttr);

    function selectAttr() {
      var labels = $(this).siblings("label");
      $(labels).each(function(){
        $(this).removeClass("checked");
      });
      $(this).next().addClass("checked");
    };

    // 改变商品数量
    var buyNum = $("#buy-num");
    $("#buy-num-minus, #buy-num-plus").on("tap", changeNum);

    function changeNum() {

      var v = $(buyNum).val()*1,
          type = $(this).attr("data-type");

      if ( type === "m" ) {
        v <= 1 ? APP.alert("数量真的已经不能再少了T^T")
               : $(buyNum).val(v - 1);
      } else if ( type === "p" ) {
        $(buyNum).val(v + 1);
      };

    };

    // 立即购买
    $("#pr-buynow").on("click", function() {
      isAllChecked(function(obj) {
    	  var data = {"sid":sid}, goods = {},quantity=$("#buy-num").val(),
    	  attrs = obj["attrs"].join(",");
    	  attrs = (attrs =='' ? '-': attrs);
    	  goods[id] = {};
    	  goods[id][attrs] = {"quantity":quantity};
    	  data["goods"] = goods;
		  var d = toArray(data, 0, "", {});
		  var fieldsHtml = "";
		  for( var o in d ) {
			fieldsHtml += "<input type=\"hidden\" name=\""+o+"\" value=\""+d[o]+"\" >";
		  }
		  $("#submit-data").html(fieldsHtml);
    	  $('#pr-form').submit();
      });
    });
    
    function insertSuccess() {
      require(["modal"], function(M) {
        M.confirm({
          title: "添加到购物车",
          text: "该商品已成功添加到购物车",
          buttons: [{
            text: "继续逛",
            close: true
          }, {
            text: "去购物车",
            click: function() {
              window.location.href = "{:url(null, 'DisShopCart', 'showCart', 'sid='.$sid.'&qid='.$qid)}";
            }
          }]
        })
      });
    };

    function isAllChecked( callback ) {

      var checkedAll = true;
      
      var selected = [];

      $(".pr-check-attr").each(function() {
        
        var checked = false;

        $(this).find("input[type='radio']").each(function() {
          $(this).prop("checked") && ( checked = true ) && (selected.push($(this).val()));
        });

        if ( !checked ) {
          var info = $(this).children(".pr-check-key").attr("data-null");
          APP.alert(info);
          checkedAll = false;
          return false;
        };

      });

      checkedAll && callback && callback( {'attrs':selected} );
      
    };    
    
    var w = $(".swiper-container").width()/3;
    $(".swiper-container,.swiper-wrapper,.swiper-slide").height(w*1.5);
    require(['__COMMON__/swiper/idangerous.swiper.js'], function(S) {
      new S(".swiper-container", {
        mode:'horizontal',
        autoplay:5000
      });
    });
    
    
    // 获取商品评价内容
    var productId = {$shopPackage.id};
    
    $.ajax({
    	type:'POST',
    	url:"{:U('Home/DisShopRate/moreRate')}",
    	data: {
    		'sid': "{$sid}",
    		"product_id": "{$shopPackage.id}"
    	},
    	success: function(data) {
    		data.extra && showComment(data.extra);
    	}
    })
    
    function showComment( data ) {
      if(data==null || data.length==0){
          return;
      }
      var html = "";
      for ( var i = 0; item = data[i]; i++ ) {
        html += "<li><p>" + item.content + "</p>"
               +"<div class='user clearfix'><span>" + item.userNickName + "</span><time>" + new Date(item.create_time*1000).Format("yyyy-MM-dd hh:mm:ss") + "</time></div>"
               +"</li>";
      };
      document.getElementById( "product-comment" ).innerHTML = "<ul class='product-comment'>" + html + "</ul>";
    };
    
    Date.prototype.Format = function(fmt) { 
      var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
      }; 
      if(/(y+)/.test(fmt)) 
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
      for(var k in o) 
        if(new RegExp("("+ k +")").test(fmt)) 
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
      return fmt; 
    };

    // 切换商品详情和评价
    var productTab = document.querySelectorAll('#product-tab a');
    [].forEach.call(productTab, function(obj){
      obj.addEventListener('click', clickTab, false);
    });

    // 切换Tab
    function clickTab() {
      [].forEach.call(productTab, function(obj){
        obj.className = '';
        document.getElementById( obj.getAttribute('data-id') ).style.display = 'none';
      });
      this.className = 'current';
      document.getElementById( this.getAttribute('data-id') ).style.display = 'block';
    }

  })();
</script>